# -*- encoding: utf-8 -*-
#
# Copyright (C) 2008 Håvard Gulldahl.
#
# Licensed under the GNU Public License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.gnu.org/licenses/gpl-2.0.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = u'<havard@gulldahl.no> Håvard Gulldahl'
__license__ = 'GPL v2'

import sys, logging, datetime

import atom

import gcontacts.gcontactsbase

try:
  from elements import Elements
except ImportError:
  sys.path.insert(0,  'C:\\dev\\gcontacts\\src')
  from elements import Elements

MS_NAMESPACE = 'http://schemas.microsoft.com/Contact'
MSP2P_NAMESPACE = 'http://schemas.microsoft.com/Contact/Extended/MSP2P'

class ContactElement(Elements):
  _namespace = MS_NAMESPACE
  _attributes = Elements._attributes.copy()
  _attributes['{%s}ElementID' % MS_NAMESPACE] = 'element_id'
  _attributes['{%s}Version' % MS_NAMESPACE] = 'version'
  _attributes['{%s}ModificationDate' % MS_NAMESPACE] = 'modificationdate'
  element_id = None
  version = None
  modificationdate = None

class ContactID(ContactElement):
  _tag = 'ContactID'
  _children = ContactElement._children.copy()
  _children['{%s}Value' % MS_NAMESPACE] = ('value',  unicode)
  def __init__(self, value=None,  text=None):
    self.value = value
    self.text = text

class ContactIDCollection(ContactElement):
  _tag = 'ContactIDCollection'
  _children = ContactElement._children.copy()
  _children['{%s}ContactID' % MS_NAMESPACE] = ('ids',  [ContactID])

  def __init__(self,  ids=None,  text=None):
    self.ids = ids or []
    self.text = text


class LabelCollection(ContactElement):
  _tag = 'LabelCollection'
  _children = ContactElement._children.copy()
  _children['{%s}Label' % MS_NAMESPACE] = ('labels',  [unicode])

  def __init__(self,  labels=None,  text=None):
    self.labels = labels or []
    self.text = text

class EmailAddress(ContactElement):
  _tag = 'EmailAddress'
  _children = ContactElement._children.copy()
  _children['{%s}Type' % MS_NAMESPACE] = ('email_type',  unicode)
  _children['{%s}Address' % MS_NAMESPACE] = ('address',  unicode)
  _children['{%s}LabelCollection' % MS_NAMESPACE] = ('labels',  LabelCollection)
  def __init__(self, email_type=None,  address=None,  labels=None,  text=None):
    self.email_type = email_type
    self.address = address
    self.labels = labels or []
    self.text = text
  def isPreferred(self):
    try:
      return 'Preferred' in self.labels.labels
    except AttributeError:
      return False

class EmailAddressCollection(ContactElement):
  _tag = 'EmailAddressCollection'
  _children = ContactElement._children.copy()
  _children['{%s}EmailAddress' % MS_NAMESPACE] = ('emails',  [EmailAddress])

  def __init__(self,  emails=None,  text=None):
    self.emails = emails or []
    self.text = text

class Name(ContactElement):
  _tag = 'Name'
  _children = ContactElement._children.copy()
  _children['{%s}FormattedName' % MS_NAMESPACE] = ('formattedname',  unicode)
  _children['{%s}FamilyName' % MS_NAMESPACE] = ('familyname',  unicode)
  _children['{%s}GivenName' % MS_NAMESPACE] = ('givenname',  unicode)
  def __init__(self, formattedname=None,  familyname=None,  givenname=None,  text=None):
    self.formattedname = formattedname
    self.familyname = familyname
    self.givenname = givenname
    self.text = text

class NameCollection(ContactElement):
  _tag = 'NameCollection'
  _children = ContactElement._children.copy()
  _children['{%s}Name' % MS_NAMESPACE] = ('names',  [Name])
  def __init__(self, names=None,  text=None):
    self.names = names or []
    self.text = text

class PhoneNumber(ContactElement):
  _tag = 'PhoneNumber'
  _children = ContactElement._children.copy()
  _children['{%s}Number' % MS_NAMESPACE] = ('number',  unicode)
  _children['{%s}LabelCollection' % MS_NAMESPACE] = ('labels',  LabelCollection)
  def __init__(self, number=None,  labels=None,  text=None):
    self.number = number
    self.labels = labels or []
    self.text = text

class PhoneNumberCollection(ContactElement):
  _tag = 'PhoneNumberCollection'
  _children = ContactElement._children.copy()
  _children['{%s}PhoneNumber' % MS_NAMESPACE] = ('numbers',  [PhoneNumber])
  def __init__(self, numbers=None,  text=None):
    self.numbers = numbers or []
    self.text = text

class Photo(ContactElement):
  _tag = 'Photo'
  _children = ContactElement._children.copy()
  _children['{%s}LabelCollection' % MS_NAMESPACE] = ('labels',  LabelCollection)
  _children['{%s}Url' % MS_NAMESPACE] = ('url',  unicode)
  _children['{%s}Value' % MS_NAMESPACE] = ('data',  str)
  def __init__(self, labels=None,  url=None,  data=None,  text=None):
    self.labels = labels or []
    self.url = url
    self.data = data
    self.text = text

class PhotoCollection(ContactElement):
  _tag = 'PhotoCollection'
  _children = ContactElement._children.copy()
  _children['{%s}Photo' % MS_NAMESPACE] = ('photos',  [Photo])
  def __init__(self, photos=None,  text=None):
    self.photos = photos or []
    self.text = text


class MSContact(ContactElement):
  _tag = 'contact'
  #_attributes = ContactElement._attributes.copy()
  _children = ContactElement._children.copy()
  _children['{%s}CreationDate' % MS_NAMESPACE] = ('creationdate',  datetime.datetime,  '%Y-%m-%dT%H:%M:%S.000%Z')
  _children['{%s}Notes' % MS_NAMESPACE] = ('notes',  unicode)
  _children['{%s}Gender' % MS_NAMESPACE] = ('gender',  unicode)
  _children['{%s}ContactIDCollection' % MS_NAMESPACE] = ('ids',  ContactIDCollection)
  _children['{%s}EmailAddressCollection' % MS_NAMESPACE] = ('emails',  EmailAddressCollection)
  _children['{%s}NameCollection' % MS_NAMESPACE] = ('names',  NameCollection)
  _children['{%s}PhotoCollection' % MS_NAMESPACE] = ('photos',  PhotoCollection)
  _children['{%s}PhoneNumberCollection' % MS_NAMESPACE] = ('numbers',  PhoneNumberCollection)

  def __init__(self, creationdate=None,  ids=None,  emails=None,  names=None,  photos=None,  text=None,  notes=None,  gender=None,  numbers=None):
    self.ids = ids or []
    self.emails = emails or []
    self.names = names or []
    self.numbers = numbers or []
    self.photos = photos or []
    self.text = text
    self.notes = notes
    self.gender = gender

  def getName(self):
    try:
      return self.names.names[0].formattedname or '%s %s' % (self.names.names[0].givenname,  self.names.names[0].familyname)
    except IndexError:
      return ''
class MSContactEntry(gcontacts.gcontactsbase.ContactEntry):
  def loadMSContact(self,  buf):
    logging.debug("loadMSContact: %s",  buf)
    c = MSContact()
    if hasattr(buf,  'read'):
      c.from_string(buf)
    else:
      c.from_file(buf)
    self.title = atom.Title(text=c.getName())
    self.content = atom.Content(text=c.notes)
    bool_string = {True: 'true',  False: 'false'}
    self.email = [ gcontacts.gcontactsbase.Email(address=e.address,  primary=bool_string[e.isPreferred()]) for e in c.emails.emails if e.address ]
    return self



if __name__ == '__main__':
  c = MSContact()
  c.from_file(sys.argv[1])
  m = MSContactEntry()
  m.loadMSContact(sys.argv[1])
  print m
